<template>
  <div>
    <a-table
      row-key="id"
      :scroll="true"
      :loading="loading"
      :data="renderData"
      :bordered="false"
      :pagination="false"
      :row-class="rowClass"
      @row-click="rowClick"
    >
      <template #columns>
        <a-table-column data-index="name" />
        <a-table-column
          title="新增"
          align="right"
          data-index="operations"
          :width="80"
        >
          <template #title>
            <a-button type="text" size="small" @click="addMethod()">
              新增
            </a-button>
          </template>
          <template #cell="{ record }">
            <a-button type="text" size="small" @click="changeMethod(record)">
              {{ record.enableFlag === '1' ? '有效' : '无效' }}
            </a-button>
          </template>
        </a-table-column>
      </template>
    </a-table>
    <invoice-add ref="invoiceAddRef" @refresh="fetchData"></invoice-add>
  </div>
</template>

<script setup lang="ts">
  import useLoading from '@/hooks/loading';
  import { defineEmits, ref } from 'vue';
  import { listRule, updateStatusRule, VoucherRuleDTO } from '@/api/invoice';
  import InvoiceAdd from '@/views/invoice/components/invoice-add.vue';
  import { useRoute } from 'vue-router';

  const { loading, setLoading } = useLoading();
  const renderData = ref<VoucherRuleDTO[]>([]);
  const invoiceAddRef = ref();
  const selectedRow = ref<string | null>(null);
  const emit = defineEmits(['change']);
  const rowClick = (record: VoucherRuleDTO) => {
    selectedRow.value = record.id;
    emit('change', record.id);
  };
  const rowClass = (record: any) => {
    return record.id === selectedRow.value ? 'select-row' : '';
  };
  const routeType = useRoute().meta.type;

  const fetchData = async () => {
    setLoading(true);
    try {
      const { data } = await listRule(routeType as string);
      renderData.value = data;
      if (renderData.value) {
        rowClick(renderData.value[0]);
      }
    } catch (err) {
      // you can report use errorHandler or other
    } finally {
      setLoading(false);
    }
  };

  const changeMethod = async (record: VoucherRuleDTO) => {
    try {
      setLoading(true);
      record.enableFlag = record.enableFlag === '1' ? '0' : '1';
      await updateStatusRule(record.id, record.enableFlag);
    } catch (e) {
      // you can report use errorHandler or other
    } finally {
      setLoading(false);
    }
  };
  const addMethod = async () => {
    invoiceAddRef.value.handleChangeVisible();
  };
  fetchData();
</script>

<style scoped lang="less">
  /* 自定义行样式 */
  :deep(.select-row) td {
    background-color: #e6e6ec !important; /* 错误行红色背景 */
  }
</style>
